const Router = require("koa-router");
const register = new Router();
const db = require("../utils/db.js");
const bodyParser = require("koa-bodyparser");
register.use(bodyParser());

//登录验证接口
register.post("/", async (ctx) => {
  // console.log(ctx.request.body)
  let username = ctx.request.body.username;
  let password = ctx.request.body.password;

  //判断数据库是否有这个账号
  let seachsql = `select * from user where username='${username}'`;

  let myarr = await new Promise((resolve, reject) => {
    return db.query(seachsql, (err, data) => {
      if (err) throw err;
      resolve(data); //扔出去一个数组赋值给myarr
    });
  });
  //判断搜索数组长度是否大于0
  if (myarr.length > 0) {
    //有账号验证密码
    // console.log(myarr);
    ctx.body = {
      code: "200",
      msg: "ishave",
      detail: "已存在该账户",
    };
  } else {
    let seachsql = `insert into user(username,password)
    values ('${username}','${password}');`;
    let myarr = await new Promise((resolve, reject) => {
      return db.query(seachsql, (err, data) => {
        if (err) throw err;
        resolve(data);
      });
    });
    let data = myarr;
    ctx.body = {
        code: "200",
        msg: "success",
        detail: "新增成功",
        data:data
      };
  }
});

module.exports = register;
